package club.zhilin.guli.service.oss.service.impl;

import club.zhilin.guli.service.oss.config.OssConfigProperties;
import club.zhilin.guli.service.oss.service.IFileService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.CannedAccessControlList;
import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author zhilin
 * @since 2022/1/19 21:23
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@EnableConfigurationProperties({OssConfigProperties.class})
public class FileServiceImpl implements IFileService {

    /**
     * 封装后的ossClient
     */
    private final OSS ossClient;
    /**
     * oss配置类
     */
    private final OssConfigProperties ossConfigProperties;

    @Override
    public String upload(InputStream inputStream, String module, String originalFileName) {
        if (!ossClient.doesBucketExist(ossConfigProperties.getBucketName())) {
            ossClient.createBucket(ossConfigProperties.getBucketName());
            ossClient.setBucketAcl(ossConfigProperties.getBucketName(), CannedAccessControlList.PublicRead);
        }
        // 构建objectName 文件路径
        String folder = new DateTime().toString("yyyy/MM/dd");
        // key
        String key = module + "/" + folder + "/" + UUID.randomUUID().toString() + originalFileName.substring(originalFileName.lastIndexOf("."));
        // 上传
        ossClient.putObject(ossConfigProperties.getBucketName(), key, inputStream);
        return "https://" + ossConfigProperties.getBucketName() + "." + ossConfigProperties.getEndpoint() + "/" + key;
    }

    @Override
    public void removeFile(String fileUrl) {
        String host = "https://" + ossConfigProperties.getBucketName() + "." + ossConfigProperties.getEndpoint() + "/";
        ossClient.deleteObject(ossConfigProperties.getBucketName(), fileUrl.substring(host.length()));
    }
}
